#!/usr/bin/env python

"Internet Time Protocol - TCP server"

import socket
import logging
import time
import struct

logging.basicConfig(level=logging.INFO)

HOSTNAME='localhost'
PORT=3737
TIME1970 = 2208988800

def main():
    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    service.bind((HOSTNAME, PORT))
    service.listen(1)
    logging.info("NTP Server accepting connections on port %d" % PORT)

    while True:
        channel, info = service.accept()
        logging.info("New client connection from '%s'" % info[0])
        t = int(time.time()) + TIME1970
        logging.info("Current timestamp is %d" % t)
        t = struct.pack("!I", t)
        channel.send(t)
        channel.close()
        logging.info("Connection closed")

if __name__ == '__main__':
    main()

